import { mount } from '@vue/test-utils'
import BookDetail from '@/views/frontView/details/index.vue'
import { useUserStore } from '@/stores/user'
import api from '@/api'
import { ElMessage } from 'element-plus'

jest.mock('@/api', () => ({
  book: {
    createBorrow: jest.fn(),
    getBookInfo: jest.fn().mockResolvedValue({
      data: { id: 1, title: '测试书籍' }
    })
  }
}))

describe('图书借阅测试套件', () => {
  let wrapper

  beforeEach(async () => {
    // 模拟登录用户
    useUserStore.mockImplementation(() => ({
      library_users: { userId: 123 },
      token: 'mock_token'
    }))

    wrapper = mount(BookDetail, {
      global: {
        mocks: {
          $route: { query: { id: 1 } }
        }
      }
    })
    
    await wrapper.vm.fetchBookInfo()
  })

  test('正常借阅流程', async () => {
    api.book.createBorrow.mockResolvedValue({ code: 200 })
    
    await wrapper.vm.openBorrowDialog()
    await wrapper.vm.handleStepAction() // 触发借阅流程
    
    expect(api.book.createBorrow).toHaveBeenCalledWith({
      userId: 123,
      bookId: 1,
      borrowDate: expect.any(String),
      returnDate: expect.any(String)
    })
  })

  test('未登录用户应重定向', async () => {
    useUserStore.mockImplementation(() => ({ 
      library_users: null 
    }))
    
    await wrapper.vm.openBorrowDialog()
    
    expect(ElMessage.error).toHaveBeenCalledWith('请先登录')
  })
})